package me.keiwu.log.service.impl;

import me.keiwu.log.dao.LogLoginDao;
import me.keiwu.log.domain.LogLogin;
import me.keiwu.log.service.LogLoginService;
import me.keiwu.pub.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.Date;

/**
 * Created by kei on 06/12/2017.
 */
@Service
@Transactional
public class LogLoginServiceImpl implements LogLoginService {

    @Autowired
    private LogLoginDao logLoginDao;

    @Override
    public Page<LogLogin> getDailyLogin(String nickName, int page, int size) {
        Specification<LogLogin> spec = (root, query, cb) -> {
            query.groupBy(root.get("userId"));
            Long todayStart = DateUtil.getDayStart(new Date()).getTime() / 1000;
            Predicate p1 = cb.not(cb.lessThan(root.get("loginTime"), todayStart));
            if (StringUtils.isNotBlank(nickName)) {
                Predicate p2 = cb.like(root.get("nickName"), "%" + nickName + "%");
                return cb.and(p1, p2);
            }
            return p1;
        };
        Sort sort = new Sort(Sort.Direction.DESC, "loginTime");
        Pageable pageable = new PageRequest(page, size, sort);
        return logLoginDao.findAll(spec, pageable);
    }

    @Override
    public Page<LogLogin> getHistoryLogin(String nickName, int page, int size) {
        Specification<LogLogin> spec = (root, query, cb) -> {
            query.groupBy(root.get("userId"));
            if (StringUtils.isNotBlank(nickName)) {
                return cb.like(root.get("nickName"), "%" + nickName + "%");
            }
            return cb.and();
        };
        Sort sort = new Sort(Sort.Direction.DESC, "loginTime");
        Pageable pageable = new PageRequest(page, size, sort);
        return logLoginDao.findAll(spec, pageable);
    }

    @Override
    public LogLogin logLogin(Long userId, String nickName, String channel, Integer loginTime) {
        LogLogin logLogin = new LogLogin();
        logLogin.setUserId(userId);
        logLogin.setNickName(nickName);
        logLogin.setLoginTime(loginTime);
        logLogin.setChannel(channel);
        logLogin.setLoginTime(DateUtil.getUnixTime());
        logLoginDao.save(logLogin);
        return logLogin;
    }
}
